package com.softa.web.common.controller;

import com.softa.common.qrcode.QrcodeParam;
import com.softa.common.sysconfig.properties.FileBootProperties;
import com.softa.common.sysconfig.support.Result;
import com.softa.common.utils.CommonUtil;
import com.softa.common.utils.DateUtils;
import com.softa.common.utils.QrCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;


/**
 * 下载
 *
 * @author yangl
 */
@Controller
@RequestMapping(value = "/file")
@Api(tags = "文件操作类")
@Slf4j
public class FileController extends BaseController {

    @Autowired
    private FileBootProperties fileBootProperties;


    /**
     * 重新命名
     *
     * @param name 原文件名
     * @return 重新命名后的名称
     */
    public String getNewFileName(String name) {
        //获取后缀
        String suffix = name.split("\\.")[1];
        // 生成随机文件名：当前年月日时分秒+五位随机数（为了在实际项目中防止文件同名而进行的处理）
        // 获取随机数
        String rannum = CommonUtil.getRandomNumber(5);
        return DateUtils.getyyyyMMddHHmmss(new Date()) + rannum + "." + suffix;
    }

    @PostMapping(value = "/upload", produces = "text/html; charset=UTF-8")
    @ResponseBody
    @ApiOperation("上传文件")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        String newFileName = null;
        if (!file.isEmpty()) {
            //获取文件名
            String realFileName = file.getOriginalFilename();
            //重命名文件
            newFileName = this.getNewFileName(realFileName);
            //文件路径
            //String path=request.getSession().getServletContext().getRealPath("/")+"upload/";
            String path = fileBootProperties.getBaseUploadDir();
            File f = new File(path + newFileName);
            //判断文件夹是否存在，不存在则创建
            if (!f.exists()) {
                f.mkdirs();
            }
            //上传
            file.transferTo(f);
        }
        return newFileName;
    }

    @PostMapping(value = "/upload1", produces = "text/html; charset=UTF-8")
    @ResponseBody
    @ApiOperation("上传文件2")
    public void upload(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
        String name = multipartRequest.getParameter("name");
        System.out.println("name：" + name);
        //获得文件名
        String realFileName = file.getOriginalFilename();
        System.out.println("文件名：" + realFileName);
        //获取路径
        String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload/";
        //创建文件
        File dirPath = new File(ctxPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        File uploadFile = new File(ctxPath + realFileName);
        PrintWriter pw = null;
        try {
            FileCopyUtils.copy(file.getBytes(), uploadFile);
            response.setContentType("text/html;charset=utf-8");
            pw = response.getWriter();
            pw.write(realFileName);
        } catch (IOException e) {
            e.printStackTrace();
//            logger.error(e.getMessage());
        } finally {
            pw.close();
        }
    }


    /**
     * 下载文件
     *
     * @param fileName
     * @param response
     */
    @GetMapping(value = "/download/{filename:.+}")
    @ApiOperation("下载文件")
    public void downLoad(@PathVariable("filename") String fileName, HttpServletResponse response) {
        //文件路径
        String path = fileBootProperties.getBaseUploadDir();
        //String path=request.getSession().getServletContext().getRealPath("/")+"upload/";
        String filePath = path + fileName;

        ServletOutputStream out = null;
        FileInputStream in = null;
        PrintWriter pw = null;
        try {
            File file = new File(filePath);
            //文件不存在
            if (!file.exists()) {
                response.setContentType("text/html;charset=utf-8");
                pw = response.getWriter();
                pw.write("<script type=\"text/javascript\">alert('文件不存在!')</script>");
            } else {
                if (fileName != null && fileName.length() > 0) {
                    out = response.getOutputStream();
                    in = new FileInputStream(file);
                    response.setContentType("application/x-msdownload;charset=utf-8");
                    response.setHeader("Content-Disposition", "attachment;filename=" +
                            URLEncoder.encode(fileName, "utf-8"));
                    if (in != null) {
                        //读取文件
                        int fileLen = 0;
                        byte[] bt = new byte[1024];
                        while ((fileLen = in.read(bt, 0, 1024)) != -1) {
                            //写入文件
                            out.write(bt, 0, fileLen);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
//            logger.error(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (pw != null) {
                    pw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查看,读取文件
     *
     * @param fileName 文件名
     * @param response
     */
    @GetMapping(value = "/showfile/{filename:.+}")
    @ApiOperation("预览文件")
    public void showFile(@PathVariable("filename") String fileName, HttpServletResponse response) {
        //文件路径
        String path = fileBootProperties.getBaseUploadDir();
        //String path=request.getSession().getServletContext().getRealPath("/")+"upload/";
        String filePath = path + "/"+fileName;
        log.info("文件路径："+filePath);

        ServletOutputStream out = null;
        FileInputStream in = null;
        PrintWriter pw = null;
        try {
            File file = new File(filePath);
            //文件不存在
            if (!file.exists()) {
                response.setContentType("text/html;charset=utf-8");
                pw = response.getWriter();
                pw.write("<script type=\"text/javascript\">alert('文件不存在!')</script>");
            } else {
                if (fileName != null && fileName.length() > 0) {
                    out = response.getOutputStream();
                    in = new FileInputStream(file);
                    //文件后缀
                    String extName = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
                    //根据文件后缀判断文件类型
                    //根据文件后缀判断文件类型
                    if (extName.equals(".DOC")) {
                        response.setHeader("Content-type", "application/msword");
                    } else if (extName.equals(".DOCX")) {
                        response.setHeader("Content-type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                    } else if (extName.equals(".PDF")) {
                        response.setHeader("Content-type", "application/pdf");
                    } else if (extName.equals(".TXT")) {
                        response.setHeader("Content-type", "text/html");
                    } else if (extName.equals(".XLS")) {
                        response.setHeader("Content-type", "application/vnd.ms-excel");
                    } else if (extName.equals(".XLSX")) {
                        response.setHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    } else if (extName.equals(".PPT")) {
                        response.setHeader("Content-type", "application/vnd.ms-powerpoint");
                    } else if (extName.equals(".PPTX")) {
                        response.setHeader("Content-type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
                    } else if (extName.equals(".BMP")) {
                        response.setHeader("Content-type", "image/bmp");
                    } else if (extName.equals(".GIF")) {
                        response.setHeader("Content-type", "image/gif");
                    } else if (extName.equals(".IEF")) {
                        response.setHeader("Content-type", "image/ief");
                    } else if (extName.equals(".JPEG")) {
                        response.setHeader("Content-type", "image/jpeg");
                    } else if (extName.equals(".JPG")) {
                        response.setHeader("Content-type", "image/jpeg");
                    } else if (extName.equals(".PNG")) {
                        response.setHeader("Content-type", "image/jpeg");
                    } else if (extName.equals(".TIFF")) {
                        response.setHeader("Content-type", "image/tiff");
                    } else if (extName.equals(".TIF")) {
                        response.setHeader("Content-type", "image/tif");
                    } else {
                        response.setHeader("Content-Disposition", "attachment;filename=" +
                                URLEncoder.encode(fileName, "utf-8"));
                    }

                    if (in != null) {
                        //读取文件
                        int fileLen = 0;
                        byte[] bt = new byte[1024];
                        while ((fileLen = in.read(bt, 0, 1024)) != -1) {
                            //写入文件
                            out.write(bt, 0, fileLen);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
//            logger.error(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (pw != null) {
                    pw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建二维码
     *
     */
    @GetMapping(value = "/qrcode/create")
    @ApiOperation("创建二维码")
    @ResponseBody
    public Result showFile() {
        QrcodeParam qrcodeParam = new QrcodeParam();
        qrcodeParam.setText("https://www.baidu.com/");
        String path = fileBootProperties.getBaseUploadDir();
        qrcodeParam.setLogoPath(path+"/222.jpg");
        qrcodeParam.setDestPath(path);
        qrcodeParam.setWords("这里是百度的地址啊，是真的啊");
        //带logo，二维码下方有文字
        Result result = Result.toSucess();
        try {
            String qrcodeName = QrCodeUtil.encode(qrcodeParam);
            result.setData(qrcodeName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.toFail();
    }

}
